import os
import re
import IPy

#ext = os.environ['EXTERNAL_VPN']
#ext = os.environ['SHELL']

subnets1 = [{'ip': '1.1.1.1', 'netmask': 18}, {'ip': '2.2.2.2', 'netmask': 20}]
subnets2 = [{'ip': '1.1.1.1', 'netmask': 18}, {'ip': '3.3.3.3', 'netmask': 20}, {'ip': '2.2.2.2', 'netmask': 10}]

# delsubnets1 = set(subnets1).difference(subnets2)
# addsubnets1 = set(subnets2).difference(subnets1)

# 使用列表迭代式的方式获取需要添加的的子网信息和需要删除的子网信息
samesubnets = [item for item in subnets2 for item2 in subnets1 if item == item2]
delsubnets1 = [item for item in subnets1 for item2 in samesubnets if item != item2]
addsubnets1 = [item for item in subnets2 for item2 in samesubnets if item != item2]

print(samesubnets)

print(delsubnets1)
print(addsubnets1)

dis = 'rule 10000 permit ip vpn-instance ly1234567890 source 192.168.1.0 0.0.0.255\r\r\r\nrule 10000 permit ip vpn-instance ly1234567890 source 192.168.2.0 0.0.0.255\r\r\r\n'

keys = {'ip', 'netmask'}
# 从字典中获取子字典

def _get_rule_subnets(displayline):
    subnets = []
    rules = re.split(r'\r+\n', displayline)
    for rule in rules:
        if rule.strip().startswith('rule'):
            values = re.split(r'\s+', rule)
            strnetmask = _get_revers_netmask(values[8])
            ip = IPy.IP(values[7] + '/' + strnetmask)
            subnets.append({'ruleindex': values[1], 'ip': values[7], 'netmask': ip.prefixlen()})
            # print(subnets)

    return subnets

def _get_revers_netmask(netmask):
    revers_netmask = ''
    for i in netmask.split('.'):
        revers_netmask += str(255 - int(i)) + '.'

    revers_netmask = revers_netmask.strip('.')
    return revers_netmask

old_subnets = _get_rule_subnets(dis)
new_subnets = [{'ip': '192.168.3.0', 'netmask': 24}, {'ip': '192.168.2.0', 'netmask': 24}, {'ip': '192.168.1.0', 'netmask': 24}]

samesubnets = [item for item in old_subnets for item2 in new_subnets
               if item['ip'] == item2['ip'] and item['netmask'] == item2['netmask']]

delsubnets = old_subnets
for item in samesubnets:
    delsubnets.remove(item)

keys = {'ip', 'netmask'}
addsubnets = new_subnets
for item in samesubnets:
    item1 = {key: value for key, value in item.items() if key in keys}
    addsubnets.remove(item1)


print(samesubnets)
print(delsubnets)
print(addsubnets)
# def function(subnet, keys):
#     return {key: value for key, value in subnet.items() if key in keys}

def _get_valid_count(count, coutarray):
    while True:
        is_exist = False
        for i in coutarray:
            if i == count:
                is_exist = True
                break

        if is_exist:
            count += 1
        else:
            break

    return count

coutarray = ['10000', '10002', '10005', '1004']

# p1 = {key: value for key, value in subnets.items() if key in keys}
# print(p1)
